import { devtools, persist, subscribeWithSelector } from "zustand/middleware";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import {getUsersList,userDelete,userRegister,updateUser,getRolesList,getUserById} from '@/api'
import { message } from "antd";

const initialState = {
    userList: [],
    getRolesLists:[],
    rolesList:[]
};

export const useUserStore = create(
    immer(
        devtools(
            subscribeWithSelector(
                persist(() => initialState, {
                    name: "users-store",
                })
            )
        )
    )
);

export const getUsersListFromApi=async()=>{
   const res=await getUsersList();
   useUserStore.setState((state)=>{state.userList=res.docs});
}

export const deleteUserFromApi=async(id)=>{
    await userDelete(id)
    getUsersList()
}

export const userRegisterFromApi=async(username,password)=>{
    await userRegister(username,password)
}

export const updateUserFromApi=async(id,username,password)=>{
    let res= await updateUser(id,{username,password});
    getUsersListFromApi()
}

export const getRolesListFromApi=async()=>{
    const res=await getRolesList();
    useUserStore.setState((state)=>{state.getRolesLists=res.docs});
}

export const getUserByIdFromApi=async(id)=>{
    const res=await getUserById(id);
    useUserStore.setState((state)=>{state.rolesList=res.roles});
}

export const updateUserRolesFromApi=async(id,roles)=>{
    await updateUser(id,roles).then((res)=>{
        message.success('更新成功');
    })
}
